package com.aipartner.util;

import com.aipartner.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 用户上下文工具类
 * 
 * @author AI伙伴团队
 * @since 2024-01-20
 */
public class UserContext {
    
    private static final ThreadLocal<Long> currentUserId = new ThreadLocal<>();
    private static final ThreadLocal<String> currentUsername = new ThreadLocal<>();
    
    /**
     * 设置当前用户信息
     */
    public static void setCurrentUser(Long userId, String username) {
        currentUserId.set(userId);
        currentUsername.set(username);
    }
    
    /**
     * 清除当前用户信息
     */
    public static void clear() {
        currentUserId.remove();
        currentUsername.remove();
    }
    
    /**
     * 获取当前登录用户
     */
    public static User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof User) {
            return (User) authentication.getPrincipal();
        }
        return null;
    }
    
    /**
     * 获取当前用户ID
     */
    public static Long getCurrentUserId() {
        return currentUserId.get();
    }
    
    /**
     * 检查是否已登录
     */
    public static boolean isAuthenticated() {
        return getCurrentUser() != null;
    }
    
    /**
     * 检查当前用户是否为VIP
     */
    public static boolean isCurrentUserVip() {
        User user = getCurrentUser();
        return user != null && user.isVip();
    }
    
    /**
     * 获取当前用户昵称
     */
    public static String getCurrentUserNickName() {
        User user = getCurrentUser();
        return user != null ? user.getNickname() : "未知用户";
    }
}
